import React, { useEffect, useRef } from 'react'
import { View } from '@tarojs/components'
import { isH5 } from '../../utils/platform'

export default function EChartsComponent({ data, chartType, width = '100%', height = '250px' }) {
  const chartRef = useRef(null)
  const chartInstance = useRef(null)
  const echartsRef = useRef(null)

  // 动态导入ECharts（仅在H5环境下）
  useEffect(() => {
    if (isH5() && !echartsRef.current) {
      import('echarts').then((echarts) => {
        echartsRef.current = echarts
        if (chartRef.current && !chartInstance.current) {
          chartInstance.current = echarts.init(chartRef.current)
        }
      }).catch((error) => {
        console.error('Failed to load echarts:', error)
      })
    }
  }, [])

  // 更新图表数据
  useEffect(() => {
    if (echartsRef.current && chartInstance.current && data && data.length > 0) {
      const option = getChartOption(data, chartType)
      chartInstance.current.setOption(option, true)
    }
  }, [data, chartType, echartsRef.current])

  // 清理图表实例
  useEffect(() => {
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose()
        chartInstance.current = null
      }
    }
  }, [])

  // 处理窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize()
      }
    }

    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [])

  // 获取图表配置
  const getChartOption = (chartData, type) => {
    // 处理数据，按时间排序
    const sortedData = [...chartData].sort((a, b) => {
      const timeA = a.createTime.replace(/-/g, '/')
      const timeB = b.createTime.replace(/-/g, '/')
      return new Date(timeA) - new Date(timeB)
    })

    // 提取时间和分数数据
    const timeLabels = sortedData.map(item => {
      const date = new Date(item.createTime.replace(/-/g, '/'))
      return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
    })

    const scores = sortedData.map(item => item.score)
    const emotions = sortedData.map(item => item.emotion)

    // 根据情感类型设置颜色
    const getEmotionColor = (emotion) => {
      switch (emotion) {
        case '积极': return '#52c41a'
        case '消极': return '#ff4d4f'
        case '中性': return '#faad14'
        default: return '#1890ff'
      }
    }

    // 基础配置
    const baseOption = {
      title: {
        text: '情感分析趋势',
        left: 'center',
        textStyle: {
          fontSize: 18,
          color: '#333',
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const dataIndex = params[0].dataIndex
          const emotion = emotions[dataIndex]
          const score = scores[dataIndex]
          const time = timeLabels[dataIndex]
          return `时间: ${time}<br/>情感: ${emotion}<br/>得分: ${score.toFixed(1)}`
        }
      },
      legend: {
        data: ['积极', '中性', '消极'],
        bottom: 10,
        itemWidth: 14,
        itemHeight: 14,
        textStyle: {
          fontSize: 14
        }
      },
      grid: {
        left: '10%',
        right: '10%',
        bottom: '20%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeLabels,
        axisLabel: {
          rotate: 45,
          fontSize: 12,
          color: '#666'
        },
        axisLine: {
          lineStyle: {
            color: '#e5e5e5'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '情感得分',
        nameTextStyle: {
          color: '#666',
          fontSize: 14
        },
        axisLabel: {
          fontSize: 12,
          color: '#666'
        },
        axisLine: {
          lineStyle: {
            color: '#e5e5e5'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0'
          }
        }
      }
    }

    if (type === 'line') {
      // 曲线图配置
      return {
        ...baseOption,
        series: [{
          name: '情感得分',
          type: 'line',
          data: scores,
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#1890ff'
          },
          itemStyle: {
            color: function(params) {
              return getEmotionColor(emotions[params.dataIndex])
            },
            borderWidth: 2,
            borderColor: '#fff'
          },
          symbol: 'circle',
          symbolSize: 8,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          }
        }]
      }
    } else {
      // 柱状图配置
      return {
        ...baseOption,
        series: [{
          name: '情感得分',
          type: 'bar',
          data: scores.map((score, index) => ({
            value: score,
            itemStyle: {
              color: getEmotionColor(emotions[index])
            }
          })),
          barWidth: '60%',
          label: {
            show: true,
            position: 'top',
            fontSize: 12,
            color: '#666',
            formatter: '{c}'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          }
        }]
      }
    }
  }

  // 只在H5环境下渲染
  if (!isH5()) {
    return null
  }

  return (
    <View className="echarts-container" style={{ width, height }}>
      <div
        ref={chartRef}
        style={{
          width: '100%',
          height: '100%'
        }}
      />
    </View>
  )
}